package com.dis.resource.service.impl;

import com.dis.common.result.PageResult;
import com.dis.pojo.dto.HospitalDTO;
import com.dis.pojo.entity.Hospital;
import com.dis.pojo.entity.Region;
import com.dis.pojo.queryDTO.HospitalPageQueryDTO;
import com.dis.pojo.vo.HospitalVO;
import com.dis.resource.mapper.HospitalMapper;
import com.dis.resource.mapper.RegionMapper;
import com.dis.resource.service.HospitalService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalMapper hospitalMapper;

    @Autowired
    private RegionMapper regionMapper;

    @Override
    public void save(HospitalDTO hospitalDTO) {
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalDTO, hospital);
        hospitalMapper.insert(hospital);
    }

    @Override
    public PageResult pageQuery(HospitalPageQueryDTO hospitalPageQueryDTO) {
        PageHelper.startPage(hospitalPageQueryDTO.getPage(), hospitalPageQueryDTO.getPageSize());
        Page<HospitalVO> page = hospitalMapper.pageQuery(hospitalPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public HospitalVO getById(Long id) {
        Hospital hospital = hospitalMapper.getById(id);
        HospitalVO hospitalVO = new HospitalVO();
        BeanUtils.copyProperties(hospital, hospitalVO);

        // 获取地区名称
        Region region = regionMapper.selectById((int) hospital.getRegionId().longValue());
        if (region != null) {
            hospitalVO.setRegionName(region.getRegionName());
        }
        return hospitalVO;
    }

    @Override
    public void update(HospitalDTO hospitalDTO) {
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalDTO, hospital);
        hospitalMapper.update(hospital);
    }

    @Override
    public void deleteById(Long id) {
        hospitalMapper.deleteById(id);
    }

    @Override
    public List<HospitalVO> listAll() {
        return hospitalMapper.listAll();
    }
}
